<?php

namespace Beerus\Modules\DesignerTag\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Doraemon\model\AdmMsgSendDetails;
use Doraemon\model\Member;
use Doraemon\service\AdmMsgSend as sAdmMsgSend;
use Doraemon\service\BadgeService;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\BusinessHomeTag\DesignerHomeTag;
use Doraemon\service\Totem\TotemService;
use Doraemon\model\Totem\TotemTypes as mTotemTypes;
use Illuminate\Support\MessageBag;
use Frieza\Modules\Totem\Actions\UpdateTotem;
use Frieza\Modules\Totem\Actions\SoldOutTotem;
use Frieza\Modules\Totem\Actions\RackTotem;
use Doraemon\service\DesignerService\DesignerHomeTag as sDesignerHomeTag;
use Beerus\Modules\DesignerTag\Actions\UpdateTag;
use Beerus\Modules\DesignerTag\Actions\offLineTag;
use Beerus\Modules\DesignerTag\Actions\onLineTag;

class DesignerTagController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $limit = [($page - 1) * $pageSize, $pageSize];
        //处理无筛选参数的情况
        $all_tag_info = DesignerHomeTag::getAllHomeTagInfo($limit);
        $all_tag_info = $all_tag_info ?: [];
        if ($request_data){
            //处理有筛选参数的情况
            if ($request_data['_sort']){
                //处理排序
                $where['ORDER'] = [$request_data['_sort']['column'] => strtoupper($request_data['_sort']['type'])];
                $where['LIMIT'] = $limit;
                $all_tag_info = DesignerHomeTag::selectByWhere($where);
            }
        }
        $total = DesignerHomeTag::count('*');
        $gridModel = new GridDataModel($all_tag_info, $total, [
            'perPage' => $pageSize,
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增标签', '', url('/admin/DesignerTag/create')));
                });
                $grid->setActionClass(DropdownActions::class);
                $grid->perPages([10, 20, 30, 40, 50, 100, 500, 1000, 2000, 5000]);
                $grid->column('id', 'Id')->sortable();
                $grid->column('tag_name', '标签名称');
                $grid->column('tag_desc', '标签描述');
                $grid->column('tag_img', '标签的icon图')->display(function(){
                    $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->tag_img, ImgUrl::IMAGE_SIZE_SQ_PHONE);
                    return '<img src = "'.$imgUrl.'" height = 60px />';
                });
                $grid->column('tag_user_type', '标签所属的用户身份')->display(function(){
                    return DesignerHomeTag::TAG_USER_TYPE_INFO[$this->tag_user_type];
                });
                $grid->column('tag_weight', '标签的权重');
                //$grid->column('tag_link', '标签的跳转链接地址');
                $grid->column('start_time', '标签展示时间')->display(function(){
                    return date("Y-m-d H:i:s",$this->start_time);
                });
                $grid->column('end_time', '标签隐藏时间')->display(function(){
                    return date("Y-m-d H:i:s",$this->end_time);
                });
                $grid->column('data_status', '标签状态')->display(function(){
                    return DesignerHomeTag::STATUS_INFO[$this->data_status];
                });
                $grid->column("admin_name", '操作人员');
                $grid->actions(function (Grid\Displayers\Actions $actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $id = $actions->row->id;
                    $actions->add(new UpdateTag);
                    if ($actions->row->data_status == DesignerHomeTag::STATUS_NORMAL){
                        $actions->add(new offLineTag);
                    }elseif ($actions->row->data_status == DesignerHomeTag::STATUS_DELETE){
                        $actions->add(new onLineTag);
                    }
                });
            });

        return $content
            ->header('标签列表')
            ->description('所有的主页标签信息')
            ->row($gridList);
    }


    /**
     * 新增标签的视图
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function create(Request $request, Content $content)
    {
        $header = '新增主页标签';
        $row = [];
        $form = new Form($row);
        $tab = new Tab();
        $tab->add($header, $form);
        //徽章所有的分类
        $allUserType = DesignerHomeTag::TAG_USER_TYPE_INFO;
        $form->text('tag_name', '标签名称')->required();
        $form->text('tag_desc', '标签的描述')->required();
        $form->select('tag_user_type','徽章适用的用户身份')->options($allUserType)->required()->default('1');
        $form->number('tag_weight','徽章权重')->required()->default(0);
        $form->multiLinkSelect('tag_link', '按钮链接');
        $form->divider();
        $form->imgUpload('tag_img', '标签的icon',true,
            ['isUpload' => true, 'isGetUrl' => true])->help('单图，有的话需要上传');
        $form->text('tag_background_color','背景色号')->default('#FEF3E5')->help('默认色号,如果有改变请找UI确认色号');
        $form->text('tag_word_color','字体色号')->default('#B58240')->help('默认色号,如果有改变请找UI确认色号');
        $form->text('tag_background_alpha','背景透明度')->default('1')->help('默认透明度,如果有改变请找UI确认');
        $form->datetime('start_time','标签开始展示时间')->format('YYYY-MM-DD HH:mm:ss')->default('');
        $form->datetime('end_time','标签隐藏时间')->format('YYYY-MM-DD HH:mm:ss')->default('');
        $form->action(url('admin/DesignerTag/save'));
        return $content
            ->header('新增主页标签')
            ->description('新增标签')
            ->breadcrumb(['text' => '添加新标签'])
            ->body($tab);
    }

    /**
     * 执行添加主页标签信息
     * @param Request $request
     * @param Content $content
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Content $content)
    {
        try {
            $params = $request->input();
            unset($params['_token']);
            sDesignerHomeTag::SaveDesignerHomeTag($params);
            return redirect(url('/admin/DesignerTag/tagList'))->with(compact('success'));
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }


    /**
     * 编辑标签的视图
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function edit(Request $request, Content $content,$id)
    {
        $header = '编辑标签信息';
        //标签适用的所有身份
        $tag_user_type = DesignerHomeTag::TAG_USER_TYPE_INFO;
        //获取标签相关的信息
        $tagInfo = DesignerHomeTag::getAllTagInfoById($id);
        $tagInfo['tag_link'] = json_decode($tagInfo['tag_link'],true);
        $tagInfo['start_time'] = date('Y-m-d H:i:s',$tagInfo['start_time']);
        $tagInfo['end_time'] = date('Y-m-d H:i:s',$tagInfo['end_time']);
        $form = new Form($tagInfo);
        $tab = new Tab();
        $tab->add($header, $form);
        //dd($group_info);
        if ($id) {
            $form->hidden('id');
        }
        $form->text('tag_name', '标签名称')->required();
        $form->text('tag_desc', '标签描述')->required();
        $form->select('tag_user_type','徽章所属分类')->options($tag_user_type)->required();
        $form->number('tag_weight','标签的权重')->required();
        $form->divider();
        $form->multiLinkSelect('tag_link', '按钮链接');
        $form->divider();
        $form->imgUpload('tag_img', '标签icon图')->help('单图，有的话需要上传');
        $form->text('tag_background_color','背景色号')->help('默认色号,如果有改变请找UI确认色号');
        $form->text('tag_background_alpha','背景透明度')->help('默认透明度,如果有改变请找UI确认');
        $form->text('tag_word_color','字体色号')->help('默认色号,如果有改变请找UI确认色号');
        $form->datetime('start_time','徽章上线时间')->format('YYYY-MM-DD HH:mm:ss')->default($tagInfo['start_time']);
        $form->datetime('end_time','徽章下线时间')->format('YYYY-MM-DD HH:mm:ss')->default($tagInfo['end_time']);
        $form->action(url('admin/DesignerTag/save'));
        return $content
            ->header('编辑标签')
            ->description('编辑标签')
            ->breadcrumb(['text' => '编辑标签信息'])
            ->body($tab);
    }
}
